package com.meida.module.bus.provider.handler;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.egzosn.pay.common.bean.RefundOrder;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.enums.PayStatusEnum;
import com.meida.common.mybatis.interceptor.UpdateInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.DateUtils;
import com.meida.module.bus.client.entity.BusAfterservice;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.enums.BalanceLogTypeEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.client.enums.PayStateEnum;
import com.meida.module.bus.client.enums.PayTypeEnum;
import com.meida.module.bus.provider.service.BusAfterserviceService;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.pay.client.entity.PayConfig;
import com.meida.module.pay.client.entity.PayInfo;
import com.meida.module.pay.provider.response.PayResponse;
import com.meida.module.pay.provider.service.PayBalanceService;
import com.meida.module.pay.provider.service.PayConfigService;
import com.meida.module.pay.provider.service.PayInfoService;
import com.meida.msg.client.entity.MsgReceive;
import com.meida.msg.provider.service.MsgReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 订单售后审核
 */
@Component
public class BusAfterServiceCheckHandler implements UpdateInterceptor<BusAfterservice> {

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusAfterserviceService busAfterserviceService;

    @Autowired
    private PayBalanceService payBalanceService;

    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private PayConfigService payConfigService;

    @Autowired
    private MsgReceiveService msgReceiveService;

    @Override
    public ResultBody validate(CriteriaUpdate cu, EntityMap params) {
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaUpdate cu, EntityMap params, BusAfterservice busAfterservice) {
        busAfterservice.setAuditTime(DateUtils.getNowDateTime());
        //审核人
        Long userId = OpenHelper.getUserId();
        busAfterservice.setReviewerId(userId);
    }

    @Override
    public void complete(CriteriaUpdate cu, EntityMap params, BusAfterservice busAfterservice) {
        Long afterServiceId = busAfterservice.getAfterServiceId();
        Integer state = FlymeUtils.getInteger(busAfterservice.getState(), 0);
        BusAfterservice afterservice = busAfterserviceService.getById(afterServiceId);
        Long orderId = afterservice.getOrderId();
        BusOrder busOrder = busOrderService.getById(orderId);
        //售后审核通过
        if (state.equals(1)) {
            //处理退款
            refundOrderAmount(afterservice, busOrder, state);
        } else {
            sendUserMessage(busOrder, state);
        }

    }

    private void refundOrderAmount(BusAfterservice afterservice, BusOrder busOrder, Integer state) {
        if (FlymeUtils.isNotEmpty(busOrder)) {
            Long orderId = busOrder.getOrderId();
            Long userId = busOrder.getUserId();
            String orderNo = busOrder.getOrderNo();
            BigDecimal payableAmount = busOrder.getPayableAmount();
            if (FlymeUtils.isNotEmpty(busOrder)) {
                //查询支付流水
                PayInfo payInfo = payInfoService.findByOutTradeNo(orderNo);
                String payType = payInfo.getPayType();
                //留币余额支付
                if (payType.equals(PayTypeEnum.LiuBi.getValue())) {
                    String title = "订单退款";
                    String body = "订单号为" + orderNo + "已退款";
                    //退回订单余额
                    //todo 需要根据支付方式进行退款(pc 有其他支付方式)
                    boolean b = payBalanceService.addBindAmount(userId, userId, payableAmount, BalanceLogTypeEnum.logType5.getValue(), title, body);
                    if (b) {
                        //修改支付流水为已退款
                        payInfo.setPayStatus(PayStatusEnum.refund.code);
                        payInfo.setReturnDate(DateUtils.getDateTime());
                        payInfo.setReturnAmount(payableAmount);
                        payInfo.setReason(afterservice.getAuditMind());
                        payInfoService.updateById(payInfo);
                        //修改订单状态为已退款
                        busOrderService.updateOrderState(orderId, "7");
                        sendUserMessage(busOrder, state);
                    }
                }
                //微信支付
                if (payType.equals(PayTypeEnum.WeiXin.getValue())) {
                    PayConfig payConfig = payConfigService.getByProperty("payType", payType);
                    PayResponse payResponse = payConfigService.getPayResponse(payConfig.getPayId(), "");
                    RefundOrder refundOrder = new RefundOrder();
                    refundOrder.setRefundNo(IdWorker.getIdStr());
                    refundOrder.setOutTradeNo(orderNo);
                    refundOrder.setOrderDate(DateUtils.getNowDate());
                    refundOrder.setRefundAmount(payableAmount);
                    refundOrder.setTotalAmount(payableAmount);
                    Map refund = payResponse.getService().refund(refundOrder);
                    System.out.println(refund.toString());
                    String result_code = (String) refund.get("result_code");
                    if (result_code.equals("SUCCESS")) {
                        //修改支付流水为已退款
                        payInfo.setPayStatus(PayStatusEnum.refund.code);
                        payInfo.setReturnAmount(payableAmount);
                        payInfo.setReturnDate(DateUtils.getDateTime());
                        payInfo.setReason(afterservice.getAuditMind());
                        payInfoService.updateById(payInfo);
                        //修改订单状态为已退款
                        busOrderService.updateOrderState(orderId, "7");
                        busOrderService.updatePayState(orderId, PayStateEnum.refund.getValue());
                        sendUserMessage(busOrder, state);
                    } else {
                        //退款失败,状态需还原
                        afterservice.setState(0);
                        busAfterserviceService.updateById(afterservice);
                        String err_code_des = (String) refund.get("err_code_des");
                        ApiAssert.failure(err_code_des);
                    }
                }

            }
        }
    }

    private void sendUserMessage(BusOrder busOrder, Integer state) {
        Integer orderType = busOrder.getOrderType();
        Long userId = busOrder.getUserId();
        String msgTitle = "";
        String msgContent = "";
        OrderTypeEnum orderTypeEnum = OrderTypeEnum.getByValue(orderType);
        if (state.equals(1)) {
            msgTitle = orderTypeEnum.getLabel() + "，申请售后成功退款通知";
            msgContent = "您申请的" + orderTypeEnum.getLabel() + "售后审核成功，支付费用已退回到您的余额账户！感谢您使用留同学APP";
        }
        if (state.equals(2)) {
            msgTitle = orderTypeEnum.getLabel() + "，申请售后成功退款通知";
            msgContent = "您申请的" + orderTypeEnum.getLabel() + "审核失败，详情请咨询客户人员！感谢您使用留同学APP";
        }
        MsgReceive msgReceive = msgReceiveService.sendMsgReceiveNotice(BusOrder.class.getSimpleName(), userId, msgTitle, msgContent);
        busOrderService.orderPushMessage(msgReceive, msgTitle, msgContent);
    }
}
